﻿using AutoMapper;
using MediatR;
using Traceability.API.Applications.Command.DeepProcessingCommand;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.Applications.CommandHandler.DeepProcessingCommandHandler
{
    public class ProcessingPlantAddCommandHandler : IRequestHandler<ProcessingPlantAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Processing_Plant> _deepRepository;
        private readonly IMapper mapper;

        public ProcessingPlantAddCommandHandler(IBaseRepository<Processing_Plant> deepRepository, IMapper mapper)
        {
            _deepRepository = deepRepository;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(ProcessingPlantAddCommand request, CancellationToken cancellationToken)
        {
            var model = mapper.Map<Processing_Plant>(request);
            if (request.Id != 0)
            {
                model.UpDataUserId = request.Id;
                model.UpDataTime = DateTime.Now;
            }
            int count = await _deepRepository.Update(model);

            APIResult<int> aPIResult = new APIResult<int>();
            if (count > 0)
            {
                aPIResult.Code = EnumCode.Ok;
                aPIResult.Data = count;
                aPIResult.Msg = "保存成功";
            }
            else
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Data = count;
                aPIResult.Msg = "保存失败";
            }
            return await Task.FromResult(aPIResult);

        }
    }
}
